package com.android.bonn.fast.net;

import com.android.bonn.fast.net.config.IOkHttpConfig;
import com.android.bonn.fast.net.config.IRetrofitConfig;
import com.android.bonn.fast.net.config.OkHttpConfig;
import com.android.bonn.fast.net.config.RetrofitConfig;
import com.google.gson.Gson;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

/**
 * User: HuangYunLin(283857754@qq.com)<br/>
 * Date: 2016-08-09<br/>
 * Time: 11:23<br/>
 * FIXME<br/>
 * 在Application 中初始化 ApiHelper<br/>
 * <code> ApiHelper.getInstance().init(getApplicationContext());</code>
 */
public final class ApiHelper {

    private static Config config;

    public static void init(IOkHttpConfig httpConfig, IRetrofitConfig retrofitConfig, Gson gson, boolean debug) {
        config = new Config(httpConfig, retrofitConfig, gson, debug);
    }

    public static void addInterceptor(Interceptor interceptor) {
        config.okHttpConfig.addInterceptor(interceptor);
    }

    public static void addNetworkInterceptors(Interceptor interceptor) {
        config.okHttpConfig.addNetworkInterceptors(interceptor);
    }

    public static void init(Gson gson, boolean debug) {
        init(new OkHttpConfig(), new RetrofitConfig(), gson, debug);
    }

    public static void build() {
        config.build();
    }

    public static <T> T createService(Class<T> clazz) {
        return config.createService(clazz);
    }

    public static void release() {
        config = null;
    }

    static class Config {

        private Retrofit mRetrofit;
        private OkHttpClient client;
        private Gson gson;

        private boolean debug = true;
        IOkHttpConfig okHttpConfig;
        IRetrofitConfig retrofitConfig;

        Config(IOkHttpConfig okHttpConfig, IRetrofitConfig retrofitConfig, Gson gson, boolean debug) {
            this.okHttpConfig = okHttpConfig;
            this.retrofitConfig = retrofitConfig;
            this.debug = debug;
            this.gson = gson;
        }

        void build() {
            client = okHttpConfig.build(debug);
            mRetrofit = retrofitConfig.build(client, gson);
        }

        <T> T createService(Class<T> clazz) {
            return mRetrofit.create(clazz);
        }
    }
}